import { request } from "../../request/index.js"
Page({

    data: {
        goodsDetail: {}
    },
    pics: [],

    onLoad: function (options) {
        const { goods_id } = options
        this.getGoodsDetail(goods_id)
    },
    async getGoodsDetail(goodsId) {
        const res = (await request({ url: '/goods/detail', data: { goods_id: goodsId } })).data
        this.pics = res.message.pics.map(item => {
            return item.pics_mid_url
        })
        this.setData({
            // 很多数据没用到，所以就只存用到的数据
            // goodsDetail: {
            //     goods_name: res.message.goods_name,
            //     goods_price: res.message.goods_price,
            //     goods_introduce: res.message.goods_introduce.replace(/\.webp/g, '.jpg'),
            //     pics: res.message.pics
            // }
            goodsDetail: res.message
        })
    },
    previewImage(e) {
        let { index } = e.currentTarget.dataset
        wx.previewImage({
            current: this.pics[index], // 当前显示图片的http链接
            urls: this.pics // 需要预览的图片http链接列表
        })
    },
    // 加入购物车
    addToCart(e) {
        let cart = wx.getStorageSync('cart') || []
        const goodsInfo = this.data.goodsDetail
        let index = cart.findIndex(item => {
            return item.goods_id === goodsInfo.goods_id
        })
        if (index === -1) {
            // 首次添加
            goodsInfo.num = 1;
            goodsInfo.checked = true;
            cart.push(goodsInfo);
        } else {
            cart[index].num++;
        }
        wx.setStorageSync('cart', cart);
        wx.showToast({
            title: '添加成功!',
            icon: "success",
            mask: true
        })
    }

})